package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.text.ParseException;
import java.text.SimpleDateFormat;


public class StrToDate extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        String value = Type.StringType.convert(args[0]);
        String format = Type.StringType.convert(args[1]);
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateFormat.convertToJavaDataFormat(format));
        java.util.Date date = null;
        try {
            date = dateFormat.parse(value);
        } catch (ParseException e) {
            return null;
        }
        Type type = getReturnType();
        return type.convert(date);
    }

    public Type getReturnType() {
        return Type.TimestampType;
    }

    public String[] getFunctionNames() {
        return new String[]{"STR_TO_DATE"};
    }
}
